package vn.keho.module.dompeto;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.bingkaimedia.merchantbeta.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import vn.keho.define.convert.JsonUtil;
import vn.keho.module.dompeto.fragment.MainFragment;
import vn.keho.module.dompeto.fragment.MenuFragment;
import vn.keho.module.dompeto.fragment.MerchantFragment;
import vn.keho.module.dompeto.fragment.PageFragment;
import vn.keho.module.dompeto.fragment.PinFragment;
import vn.keho.module.dompeto.fragment.QrCodeFragment;
import vn.keho.module.dompeto.fragment.ServiceFragment;
import vn.keho.module.dompeto.fragment.SettingFragment;
import vn.keho.module.dompeto.fragment.ThemeFragment;
import vn.keho.module.dompeto.model.ChannelModel;
import vn.keho.module.dompeto.model.PageModel;
import vn.keho.module.dompeto.model.QrCodeModel;
import vn.keho.module.dompeto.model.ServiceModel;
import vn.keho.module.dompeto.model.TestWalletProfile;
import vn.keho.module.dompeto.model.ThemeModel;
import vn.keho.module.dompeto.model.WalletProfile;
import vn.keho.module.dompeto.rest.DompetoDefine;
import vn.keho.module.dompeto.rest.DompetoParam;
import vn.keho.module.dompeto.rest.DompetoRequest;
import vn.keho.module.dompeto.socket.TransactionSocket;
import vn.keho.module.dompeto.sqlite.DompetoSqliteHelper;
import vn.keho.module.dompeto.utils.ThemeUtil;

public class MerchantActivity extends FragmentActivity implements PageFragment.OnPageFragmentListener {
    private Button btnMenu, btnHome;
    private Button btnInbox, notifyBadge;
    private static MainFragment instance;

    /**
     * DrawerLayout
     */
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private MerchantFragment merchantFragment;
    private ServiceFragment serviceFragment;
    private QrCodeFragment qrCodeFragment;
    private MenuFragment menuFragment;
    private MainFragment mainFragment;
    private ThemeFragment themeFragment;
    private PinFragment pinFragment;

    private DompetoSqliteHelper dompetoSqliteHelper;

    private ProgressDialog progressDialog;
    private int count = 0;

    private WalletProfile walletProfile;
    private List<PageModel> listPageModel = new ArrayList<PageModel>();


    private TransactionSocket transactionSocket;


    public static MainFragment getInstance() {
        return instance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchant);

        dompetoSqliteHelper = new DompetoSqliteHelper(this);

        btnMenu = (Button) findViewById(R.id.btnMenu);
        btnMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });


        btnHome = (Button) findViewById(R.id.btnHome);
        btnHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchFragment(MerchantFragment.MERCHANT_FRAGMENT_ID);
            }
        });

        btnInbox = (Button) findViewById(R.id.btnInbox);
        notifyBadge = (Button) findViewById(R.id.notifyBadge);


        setUpDrawerLayout();

        switchFragment(MerchantFragment.MERCHANT_FRAGMENT_ID);

        transactionSocket = TransactionSocket.getInstance(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void setUpDrawerLayout() {

        menuFragment = (MenuFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_left);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        // set a custom shadow that overlays the main content when the drawer opens
        drawerLayout.setScrimColor(Color.TRANSPARENT);
        //mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        //mDrawerLayout.setDrawerShadow(new ColorDrawable(Color.TRANSPARENT), GravityCompat.START);
        // set up the drawer's list view with items and click listener

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,                    /* host Activity */
                drawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_launcher,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (drawerView.getId() == R.id.navigation_drawer_left) {
                    if (!menuFragment.isAdded()) {
                        return;
                    }
                }

                supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);

                if (drawerView.getId() == R.id.navigation_drawer_left) {
                    if (!menuFragment.isAdded()) {
                        return;
                    }
                }

                supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);

                LinearLayout frameLayout = (LinearLayout) findViewById(R.id.drawerLayoutContent);
                if (drawerView.getId() == R.id.navigation_drawer_left) {
                    frameLayout.setX(slideOffset * drawerView.getWidth());
                } else {
                    frameLayout.setX(-slideOffset * drawerView.getWidth());
                }

            }
        };
        // Defer code dependent on restoration of previous instance state.
        drawerLayout.post(new Runnable() {
            @Override
            public void run() {
                actionBarDrawerToggle.syncState();
            }
        });

        drawerLayout.setDrawerListener(actionBarDrawerToggle);
    }

    private int currentFragmentIndex = MainFragment.MAIN_FRAGMENT_ID;

    private ServiceModel serviceModel;
    private QrCodeModel qrCodeModel;

    private void switchFragment(int fragmentIndex) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (fragmentIndex != currentFragmentIndex) {
            //Remove
            switch (currentFragmentIndex) {
                case MerchantFragment.MERCHANT_FRAGMENT_ID:
                    if (merchantFragment != null && !merchantFragment.isDetached()) {
                        transaction.detach(merchantFragment);
                    }
                    break;

                case ServiceFragment.SERVICE_FRAGMENT_ID:
                    if(serviceFragment != null && !serviceFragment.isDetached()) {
                        transaction.detach(serviceFragment);
                    }
                    serviceFragment = null;
                    break;
                case QrCodeFragment.QRCODE_FRAGMENT_ID:
                    if(qrCodeFragment != null && !qrCodeFragment.isDetached()) {
                        transaction.detach(qrCodeFragment);
                    }
                    qrCodeFragment = null;
                    break;
            }
        }
        currentFragmentIndex = fragmentIndex;
        switch (fragmentIndex) {
            case MerchantFragment.MERCHANT_FRAGMENT_ID:
                if (merchantFragment == null) {
                    merchantFragment = MerchantFragment.newInstance();
                    transaction.add(R.id.fragmentContent, merchantFragment);
                } else {
                    transaction.attach(merchantFragment);
                }
                break;
            case ServiceFragment.SERVICE_FRAGMENT_ID:
                if (serviceFragment == null) {
                    serviceFragment = ServiceFragment.newInstance(serviceModel);
                    transaction.add(R.id.fragmentContent, serviceFragment);
                } else {
                    transaction.attach(serviceFragment);
                }
                break;
            case QrCodeFragment.QRCODE_FRAGMENT_ID:
                if (qrCodeFragment == null) {
                    qrCodeFragment = QrCodeFragment.newInstance(qrCodeModel);
                    transaction.add(R.id.fragmentContent, qrCodeFragment);
                } else {
                    transaction.attach(qrCodeFragment);
                }
                break;
            default:

                break;
        }

        transaction.commit();
        getSupportFragmentManager().executePendingTransactions();
    }

    public void onSelectService(ServiceModel serviceModel) {
        this.serviceModel = serviceModel;
        drawerLayout.closeDrawers();
        switchFragment(ServiceFragment.SERVICE_FRAGMENT_ID);
    }

    public void onGenerateQrCode(QrCodeModel qrCodeModel) {
        this.qrCodeModel = qrCodeModel;
        drawerLayout.closeDrawers();
        switchFragment(QrCodeFragment.QRCODE_FRAGMENT_ID);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        transactionSocket.onDestroy();
    }

    public void onInboxUpdateNotify(int notifyNumber) {
        notifyBadge.setText(notifyNumber + "");
        if(notifyNumber == 0) {
            notifyBadge.setVisibility(View.INVISIBLE);
        } else {
            notifyBadge.setVisibility(View.VISIBLE);
        }
    }
}
